package com.crypto;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import net.iharder.Base64;

public class Hashing {
	
	private static final String HASHING_TECHNIQE="SHA-512";
	
	public static String generateHash(String input) { 
		MessageDigest digest=null;
		String base64Hash=null;
		try {
			digest = MessageDigest.getInstance(HASHING_TECHNIQE);
			byte[] hashedBytes = digest.digest(input.getBytes());
			base64Hash = Base64.encodeBytes(hashedBytes);
		} catch (NoSuchAlgorithmException e) {
			System.out.println(e.getMessage());
		}
		
		return base64Hash;
   }
	
	
	private static byte[] generateSalt() {
        SecureRandom random = new SecureRandom();
        byte bytes[] = new byte[128];
        random.nextBytes(bytes);
        return bytes;
    }
	
	
	public static String generateSaltBase64 () {
		byte salt[]= generateSalt();
		String base64Salt=Base64.encodeBytes(salt);
		return base64Salt;
	}
	
	public static void main(String[] args) {
		String passwd="ace123";
		System.out.println("Just Hash: "+Hashing.generateHash(passwd));
		System.out.println("----------------");
		String base64Salt=generateSaltBase64();
		System.out.println("Salt: "+base64Salt);
		System.out.println("----------------");
		String base64HashWithSalt=generateHashWithSaltBase64(passwd,base64Salt);
		System.out.println("Hash with Salt: "+base64HashWithSalt);
	}
	
	
	public static String generateHashWithSaltBase64(String input, byte[] salt) {
		MessageDigest digest=null;
		String base64Hash=null;
		try {
			digest = MessageDigest.getInstance(HASHING_TECHNIQE);
			digest.reset();
			digest.update(salt);
			byte[] hashedBytes = digest.digest(input.getBytes());
			base64Hash = Base64.encodeBytes(hashedBytes);
		} catch (NoSuchAlgorithmException e) {
			System.out.println(e.getMessage());
		}

		return base64Hash;
	}
	
	public static String generateHashWithSaltBase64(String input, String salt) {
		if(salt!=null)
			return generateHashWithSaltBase64(input, salt.getBytes());
		else
			return null;
	}
	
}
